package com.hfh.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author hfh
 * @Date 2022 09 13 20 15
 **/
public class ServerDemo {
    public static final List<Socket> sockets = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(6666);

        while (true){
            Socket s = ss.accept();
            sockets.add(s);
            new ServerThread(s).start();
        }
    }
}

class ServerThread extends Thread {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            while (true) {
                UserInfo userInfo = (UserInfo) ois.readObject();

                String respMsg = userInfo.getName() + ": " + userInfo.getMsg();
                System.out.println(respMsg);

                for (Socket s: ServerDemo.sockets){
                    PrintWriter pw = new PrintWriter(s.getOutputStream());
                    pw.println(respMsg);
                    pw.flush();
                }
            }
        }catch (Exception e){
            e.getStackTrace();
        }
    }
}
